const Router = require('koa-router')
const router = new Router()
const Mock = require('mockjs')

let { list } = Mock.mock({
  'list|50': [
    {
      id: '@id',
      title: '@ctitle',
      address: '@county(true)',
      image: '@image(50x50, @color, image)',
      'type|1': ['已下单', '已付款', '待发货', '已发货', '已收货', '待评价'],
      'price|10-1000': 1,
    },
  ],
})

// 列表请求
router.get('/lists', (ctx) => {
  const { search, type, price_gte, price_lte } = ctx.request.query
  let copyList = [...list]
  // 是否模糊搜索
  if (search) {
    copyList = copyList.filter((v) => {
      return JSON.stringify(v).includes(search)
    })
  }
  console.log(copyList)
  // 是否精确查找
  if (type && type.trim() !== '全部') {
    copyList = copyList.filter((v) => {
      return v.type === type
    })
  }
  console.log(copyList)
  // 是否价格区间查找

  if (price_gte || price_lte) {
    let min = price_gte || 0
    let max = price_lte || Infinity
    copyList = copyList.filter((v) => {
      return v.price > min && v.price < max
    })
  }
  console.log(copyList)
  ctx.body = {
    code: 200,
    data: copyList,
    message: 'ok',
  }
})
// 图标接口
router.get('/echarts/list/type', (ctx) => {
  const data1 = []
  const data2 = []
  list.forEach((v, i) => {
    const index = data1.indexOf(v.type)
    if (index !== -1) {
      data2[index]++
    } else {
      data1.push(v.type)
      data2.push(1)
    }
  })
  ctx.body = {
    code: 200,
    data: {
      title: {
        text: '我的标题',
      },
      xAxis: {
        data: data1,
      },
      yAxis: {},
      series: [
        {
          name: '销量',
          type: 'bar',
          data: data2,
        },
      ],
    },
    message: 'ok',
  }
})

// 列表删除
router.delete('/list/:id', (ctx) => {
  // 1. 获取ID
  const { id } = ctx.params
  // 2. 删除数据
  list = list.filter((v) => v.id !== id)
  ctx.body = {
    code: 200,
    data: list,
    message: 'ok',
  }
})

// 列表修改
router.post('/list/:id', (ctx) => {
  // 1. 获取id
  const { id } = ctx.params
  // 2. 获取修改的健值对
  const data = ctx.request.body
  // 3. 根据id 查找数据
  const item = list.find((v) => v.id === id)
  // 4. 对象合并
  Object.assign(item, data)

  ctx.body = {
    code: 200,
    data: item,
    message: 'ok',
  }
})
// 列表添加
router.put('/list', (ctx) => {
  // 1。获取添加的数据
  const data = ctx.request.body
  const addData = {
    ...data,
    id: Mock.Random.id(),
  }
  // 2. 添加数据
  list.unshift(addData)

  ctx.body = {
    code: 200,
    data: addData,
    message: 'ok',
  }
})

module.exports = router
